<template>
    <div ref="containerRef" class="courseContentExerciseView">
        <!-- 可拖拽的进度卡片 -->
        <div class="progress-card" :style="{ left: position.x + 'px', top: position.y + 'px' }" >
            <div class="card-header">
                <div class="title" @mousedown="startDrag">答题进度</div>
                <el-button class="action-btn" size="small" @click="expand">{{ collapsed ? "展开" : "收起" }}</el-button>
            </div>
            <div v-if="!collapsed" class="card-body">
                <div class="progress-group">
                    <div class="progress-bar" v-for="(exercises, index) in publishHomework?.homeworkInfo?.exercises"
                    :class="{ 'active': index < selectedExerciseIndex, 'select': index == selectedExerciseIndex }" :key="exercises.exercisesId"
                    @click="selectedExerciseIndex = index">
                        {{ index + 1 }}
                    </div>
                </div>
            </div>
        </div>
        <!-- 按钮 -->
        <div class="buttons">
            <div class="button"
            :class="selectedExerciseIndex > 0 ? 'normal' : 'disabled'" @click="() => {
                if (selectedExerciseIndex <= 0) return;
                selectedExerciseIndex--;
            }">上一题</div>
            <div class="button"
            :class="selectedExerciseIndex < publishHomework?.homeworkInfo?.exercises.length - 1 ? 'normal' : 'disabled'" @click="()=>{
                if (selectedExerciseIndex >= publishHomework?.homeworkInfo?.exercises.length - 1) return;
                selectedExerciseIndex++;
            }" v-if="selectedExerciseIndex < publishHomework?.homeworkInfo?.exercises.length - 1">下一题</div>
            <div class="button normal" v-else>提交</div>
        </div>
        <div class="exerciseContent">
            <CourseContentExerciseContent class="exerciseContent" :index="selectedExerciseIndex + 1"
            :exercisesScore="publishHomework?.homeworkInfo?.exercises[selectedExerciseIndex]?.exerciseScore"
            :exercisesId="publishHomework?.homeworkInfo?.exercises[selectedExerciseIndex]?.exercisesId"
            :previewMode="false" :writeMode="false" />
        </div>
    </div>
</template>

<script lang="ts">
import { computed, ref, defineComponent, onMounted, onUnmounted, watch, nextTick } from "vue";
import { useRoute } from "vue-router";
import CourseContentExerciseContent from '@/components/course/CourseContentExerciseContent.vue';
import { homeworkApi } from "@/api/course/Course";
import { PublishHomework } from "@/types/Course";

export default defineComponent({
    name: 'courseContentExercise',
});
</script>

<script setup lang="ts">
    const { params } = useRoute();
    const route = useRoute();
    const courseId = ref(params.courseId);
    console.log(courseId.value);
    const selectedExerciseIndex = ref(0);
    const publishHomework = ref<PublishHomework>(null);
    
    // 进度卡片折叠
    const collapsed = ref(true);
    // 进度卡片可拖拽
    const position = ref({ x: 0, y: 0 });
    const dragging = ref(false);
    const startX = ref(0);
    const startY = ref(0);
    const containerRef = ref<HTMLElement | null>(null);
    const cardRef = ref<HTMLElement | null>(null);
    
    const startDrag = (e: MouseEvent) => {
        dragging.value = true;
        startX.value = e.clientX - position.value.x;
        startY.value = e.clientY - position.value.y;
    
        document.addEventListener("mousemove", onDrag);
        document.addEventListener("mouseup", stopDrag);
    };
    const onDrag = (e: MouseEvent) => {
        if (!dragging.value || !containerRef.value) return;
    
        const container = containerRef.value.getBoundingClientRect();
        const card = cardRef.value?.getBoundingClientRect();
        if (!card) return;
    
        let newX = e.clientX - startX.value;
        let newY = e.clientY - startY.value;
    
        // 限制卡片不会超出容器边界
        newX = Math.max(0, Math.min(newX, container.width - card.width));
        newY = Math.max(0, Math.min(newY, container.height - card.height));
    
        position.value.x = newX;
        position.value.y = newY;
    };
    const stopDrag = () => {
        dragging.value = false;
        document.removeEventListener("mousemove", onDrag);
        document.removeEventListener("mouseup", stopDrag);
    };

    // 展开
    const expand = () => {
        if (!containerRef.value) return;
    
        collapsed.value = !collapsed.value;
        
        nextTick(()=>{
            const container = containerRef.value.getBoundingClientRect();
            const card = cardRef.value?.getBoundingClientRect();
            if (!card) return;
    
            // 限制卡片不会超出容器边界
            const newX = Math.max(0, Math.min(position.value.x, container.width - card.width));
            const newY = Math.max(0, Math.min(position.value.y, container.height - card.height));
    
            position.value.x = newX;
            position.value.y = newY;
        });
    };
    
    // 计算已答题目的百分比
    const progressWidth = computed(() => {
        return `${(selectedExerciseIndex.value / publishHomework.value?.homeworkInfo?.exercises.length) * 100}%`;
    });
    
    // 监听组件加载，初始化 cardRef
    onMounted(() => {
        cardRef.value = document.querySelector(".progress-card");
    });
    
    onUnmounted(() => {
        document.removeEventListener("mousemove", onDrag);
        document.removeEventListener("mouseup", stopDrag);
    });

    
    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    const homeworkId = ref(null);
    // route.query.chapterId
    // 监听路由参数的变化
    watch(() => route.query.homeworkId, async (newvValue) => {
        homeworkId.value = parseSafeInt(newvValue);

        // 获取题目列表
        if (homeworkId.value)
        {
            selectedExerciseIndex.value = 0;
            publishHomework.value = await homeworkApi.publish.getPublishHomework(homeworkId.value);
        }
        
        nextTick(()=>{
            if (!containerRef.value) return;
            console.log("资源ID" + newvValue);
            const container = containerRef.value.getBoundingClientRect();
            const card = cardRef.value?.getBoundingClientRect();
            if (!card) return;
            position.value.x = container.width - card.width;
            position.value.y = 60;
        })
    },
    { immediate: true });
</script>

<style scoped>
.courseContentExerciseView {
    position: relative;
    width: 100%;
    height: 100%;
    min-height: 500px;
    min-width: 500px;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

/* 可拖拽的小卡片 */
.progress-card {
    position: absolute;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    z-index: 2;
}
.progress-card .card-header {
    width: 100%;
    min-width: 155px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    border-radius: 8px;
}/* 进度条 */
.progress-card .card-header::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: v-bind(progressWidth); /* 动态宽度 */
    background: rgba(65, 185, 255, 0.5); /* 蓝色半透明进度条 */
    transition: width 0.3s ease-in-out;
}
.progress-card .card-header .title {
    position: relative;
    height: 100%;
    width: 100%;
    padding: 10px 10px;
    padding-right: 80px;
    color: rgba(0, 0, 0, 0.6);
    background-color: rgba(255, 255, 255, .1);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    -moz-backdrop-filter: blur(10px);
    -ms-backdrop-filter: blur(10px);
}
.progress-card .card-header .action-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
}

.progress-card .card-body {
    padding: 10px;
}

.progress-card .card-body .progress-group {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
}
.progress-card .card-body .progress-group .progress-bar { 
    width: 35px;
    height: 35px;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    font-size: 14px;
    border: 2px solid rgba(65, 185, 255, 1);
    color:rgba(65, 185, 255, 1);
}
.progress-card .card-body .progress-group .progress-bar.select {
    background-color: rgba(65, 185, 255, .35);
}
.progress-card .card-body .progress-group .progress-bar.active {
    background-color: rgba(65, 185, 255, 1);
    color: rgba(255, 255, 255, 1);
}

.buttons {
    width: 100%;
    padding-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.buttons .button {
    padding: 5px 20px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
}
/* 正常按钮 */
.buttons .button.normal {
    background-color: rgba(65, 185, 255, 1);
    color: #fff;
}
/* 禁用按钮 */
.buttons .button.disabled {
    background-color: rgba(185, 185, 185, 1);
    color: #fff;
}

.exerciseContent {
    width: 100%;
    height: 100%;
    padding: 0px;
}

</style>
